package cn.gjxblog.validation.mvc.demo1;

import org.springframework.http.HttpEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class MethodArgumentNotValidExceptionHandler {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public HttpEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex){
        BindingResult bindingResult = ex.getBindingResult();

        StringBuilder stringBuilder = new StringBuilder();
        for (FieldError error : bindingResult.getFieldErrors()) {
            String field = error.getField();
            Object value = error.getRejectedValue();
            String msg = error.getDefaultMessage();
            String message = String.format("错误字段：%s，错误值：%s，原因：%s；", field, value, msg);
            stringBuilder.append(message).append("\r\n");
        }
        return new HttpEntity(stringBuilder);
    }
}
